package alipay

import (
	"github.com/gin-gonic/gin"
	"github.com/smartwalle/alipay/v3"
	"go-admin/app/admin/models"
	orm "go-admin/common/global"
	"go-admin/common/log"
	"go-admin/tools"
	"reflect"
	"strconv"
)

/**
* @Description:
* @Author: yuweizhu
* @Date: 2020/11/16 12:34 上午
**/
var (
	err error
	// sandbox
	appId = "2016091800536867"
	privateKey = "MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCTqftsHUDl2KvpKuQCQklNi4zeLF4CbxKaVvRvYIdTccwMGbjkxy0bWtDyrfJCLhjmYPeNgKRUfJEs/3eGOVFvfHBbePtNqprP5/zoH+msKpWxQ+89l4m0ETnpOYrCZ6jfYaoUt57sygVMTL+AqtCemjsrdlVYJzJqevuKIeKKh0KfY8zZKF5QmzaZbtYWlnWDOb2t1hSDmdZbgkUPKjh9qzVD6A+V80lFprM1S0eeLOnulgsQn7ju/CfS6o5Fk90AqZbPvTyI9MXcknEcwQ2I7mTWc8lUqFVvhGsDvF2q5+Xrkiyc2sQJW/Yws+Cd1J9Jn1cwhHPkfwTzT9gn9I/rAgMBAAECggEAKT5kJElzc/913NWHA/6BvPAKc4/O3j0p5AP/mBBNHAh/5q1UkEn1lltiWzYsoUGA4PAalOJmg9abMgdU2h+uWEZYl6QOBR5uyT1RzYAEY3stfmqsKvbllm7tTvAsiqorZ+E+gTTcZeTzX+Fb59NOG86WUkhmBA5GrakWEvnt7aT2je8aA8at5IEhAJ3Fob8Jz7qL/KQZeN7vLGElCTpEgavrETbF8gBJe0QPtwXrBZghuMLA+AINAoKUFINkgyfp515CjE/Jl7YsmqTPyfxS4gRUf7TJMO2Z3qaBZdOu341LXUJEqV8fUmSPh/vRNFX0tzFBPougAvJcRR+3FgCKMQKBgQDb6s4tJzNtM0UcUbVgZMq8kaaxZFshmy0tH2sGxeRjnPP8jaYBfn0mKrjTmRgedr5e0E8mRtMQK9qY068li4r2WFk65yWUMSEpSiTz5kj45vQVDKGmJHgUdWn1ITa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NixVby+pgSPKfa8GvPRIw6oWwEi0T+uMZpWAB23Kc4K164oukuxAR0qzn3GzcuJooyOcQKBgBVSWjp/JwZhGxg4t40vYgYU0PvlTI1Ww4OuVfeNPqr9hUueVIims4hSzCsKg1OG5TrlrZNFbZMuzq4CAlXZ8y0gKqjreMeeweOmIOJDsGUmxMtaEtji2NcwIT+4aN5IcnB+OAKl3lodkvLIhfM/mGCKnzaMmkun3rqJsQMacAan"
	aliPublicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAgtUdxl/o2Zk+OpsDzdWpD3IZQX2D6et9ktMF5KFMDMwhj3lf0Nr9AMyel3BnayEDE7+Hixp8KinxV6ZEBqxpI89v4D3h6klNTK0GcOyR0b5UQtZg++aGYaXhrDsoJpmupk7pAlGlW8lcB2BTnmw96AMyhzqIETx/19xv3lJf3v8g8e4lOgpCtZ1BAP3UdS+E5Pre4mfqgDTFu3BoqwitA8QvDgGhdgoEo9W/YxTH+txtlPZEhpVpmC8w8pvRbJTxSnLBcYlSNhiGM0Mw939E3i9zjEBA7/0sUKh20FguvqBtR+WlnvodWzyK29uEUBykh1/wwWjVx9rQCAe8e2xZawIDAQAB"
	isProduction = true
	alipayClient *alipay.Client
	notifyUrl = "http://www.ddlink.vip/goadminapi/api/v1/recharge/callback"
	returnUrl = "http://www.ddlink.vip/admin/#/torder/add"
)

func init()  {
	if !isProduction {
		alipayClient, err = alipay.New(appId, privateKey, isProduction)
		if err != nil {
			panic(err)
		}
	} else {
		alipayClient, err = alipay.New(appIdProduction, privateKeyProduction, isProduction)
		if err != nil {
			panic(err)
		}
	}
	_ = alipayClient.LoadAliPayPublicKey(aliPublicKey)
}
// 创建支付订单
func CreateAlipayOrder(orderNo string, amount int, product string) string {
	var p = alipay.TradePagePay{}
	p.NotifyURL = notifyUrl
	p.ReturnURL = returnUrl
	p.Subject = product
	p.OutTradeNo = orderNo
	p.TotalAmount = strconv.Itoa(amount)
	p.ProductCode = "FAST_INSTANT_TRADE_PAY"

	url, err := alipayClient.TradePagePay(p)
	if err != nil {
		panic(err)
	}
	return url.String()
}

// 支付回调
func AlipayOrderCallback(c *gin.Context)  {
	log.Info("alipay callback message enter")
	var noti, err = alipayClient.GetTradeNotification(c.Request)
	log.Info("alipay callback message enter, %+v, %+v", noti, err)
	tools.HasError(err, "支付失败", 500)
	if noti == nil {
		alipay.AckNotification(c.Writer)
		return
	}
	log.Infof("alipay callback message: %+v", noti)
	tx := orm.GetDb().Begin()
	var data models.TOrder
	if noti.TradeStatus == alipay.TradeStatusWaitBuyerPay {
		data.Status = 1
	} else if noti.TradeStatus == alipay.TradeStatusClosed {
		data.Status = 3
	} else {
		data.Status = 2
	}
	order, err := data.Get(noti.OutTradeNo)
	if err != nil || reflect.DeepEqual(order, models.TOrder{}) {
		alipay.AckNotification(c.Writer)
		return
	}
	_ = data.Update(tx, noti.OutTradeNo)
	if data.Status != 2 {
		tx.Commit()
		alipay.AckNotification(c.Writer)
		return
	}

	var account models.TAccount
	var user models.SysUser
	account.UserId = order.UserId
	account.Amount = order.Amount
	err = account.IncreaseAmount(tx)
	if err != nil {
		tx.Rollback()
		tools.HasError(err, "添加失败", 500)
		alipay.AckNotification(c.Writer)
		return
	}
	account = models.TAccount{}
	account.UserId = order.UserId
	resultAccount, err := account.Get()
	if err != nil {
		tx.Rollback()
		tools.HasError(err, "用户不存在", 500)
		alipay.AckNotification(c.Writer)
		return
	}

	if resultAccount.SumAmount == 0 {
		user.StarLevel = 0
	} else if resultAccount.SumAmount < 500 {
		user.StarLevel = 0
	} else if resultAccount.SumAmount < 1000 {
		user.StarLevel = 1
	} else if resultAccount.SumAmount < 2000 {
		user.StarLevel = 2
	} else {
		user.StarLevel = 3
	}
	user.UserId = int(data.UserId)
	_, _ = user.Update(tx, user.UserId)
	tx.Commit()
	alipay.AckNotification(c.Writer)
}